package com.cloudxingkong.dianyinke.Student.Ui;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.config.Constans;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.SlideTimerShaft.Tool;
import com.cloudxingkong.dianyinke.SlideTimerShaft.YMDDatePickerDialog;
import com.cloudxingkong.dianyinke.Student.Utils.WxUtil;
import com.cloudxingkong.dianyinke.Student.bean.OrderReq;
import com.cloudxingkong.dianyinke.Student.bean.OrderSeverCallback;
import com.cloudxingkong.dianyinke.Student.bean.StudentAddr;
import com.cloudxingkong.dianyinke.Uri.studentUri.StudentUri;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

/**
 * @确认订单
 */
public class ConfirmOrder extends AppCompatActivity {
    private SharedPreferences sharedPreferences;

    private LinearLayout ll_dizhi;
    private Button btn_OrdersConfirmation;
    /*
    申明加减数量
     */
    private ImageButton imagebtn_jia;
    private ImageButton imagebtn_jian;
    private TextView tvNum;
    private TextView tvSum;
    private TextView tvPrice;
    private int NUM_CURRENT=0;
    int num = 0;
    int sum = 0;
    private GoogleApiClient client;

    //授课方式 授课时间 支付方式 可用积分

    private EditText qrdd_keyongjifen;
    private EditText time_editText;
    private String time;
    private String shoukejifen;
    private Spinner zfspinner;
    private String zfSpinner;
    private static final String []items = {"微信支付","支付宝支付","积分兑换"};
    private static final String []item = {"学生自去"};

    private Spinner fsspinner;
    private String fsSpinner ;
    private ArrayAdapter<String >stringArrayAdapter;

    private TextView tvstudentName,tvstudentPhone,tvstudentAddr;
    private TextView qrdd_tv_title,qrdd_tv_content;

    private ImageView imageView;
    private String  teacherID;
    private String sessionID;
    /**微信支付*/
    private IWXAPI wxapi;
    private String lessonID;
    private String recphone;
    private String recname;
    private String classaddr;
    private YMDDatePickerDialog pickerDialog;
    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order);
        //微信支付
        wxapi = WXAPIFactory.createWXAPI(this,Constans.APP_ID,false);
        wxapi.registerApp(Constans.APP_ID);

        init();
        queryStudentsAddress();//学生添加地址
        clickListener();
        //接收约课传的值
        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        String content = intent.getStringExtra("content");
        String price = intent.getStringExtra("price");
        String pic = intent.getStringExtra("teacherPic");
        teacherID = intent.getStringExtra("teacherID");
        lessonID = intent.getStringExtra("lessonID");
        ImageLoader.getInstance().displayImage(pic, imageView);

        qrdd_tv_title.setText(title);
        qrdd_tv_content.setText(content);
        tvPrice.setText(price);
    }
    //订单地址
    private void queryStudentsAddress() {
        sharedPreferences = ConfirmOrder.this.getSharedPreferences("data_dyk", 0);
        final String sessionid = CookieHelper.getSessionID(sharedPreferences);
        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + StudentUri.QUERYSTUDENTADDRESS);
        params.addHeader("cookie", sessionid);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result!=null&&!result.equals("")){
                    Log.e("test", "学生默认地址信息 " + result);
                    Message msg = handler.obtainMessage();
                    msg.what = 3;
                    msg.obj = result;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("test", "学生默认地址信息失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    //初始化控件
    private void init() {
        sharedPreferences = ConfirmOrder.this.getSharedPreferences("data_dyk", 0);
        sessionID = CookieHelper.getSessionID(sharedPreferences);

        btn_OrdersConfirmation = (Button) findViewById(R.id.btn_OrdersConfirmation);
        qrdd_keyongjifen = (EditText) findViewById(R.id.qrdd_keyongjifen);//可用积分
        imageView = (ImageView) findViewById(R.id.qrdd_image);
        //加减按钮
        imagebtn_jia = (ImageButton) findViewById(R.id.imagebtn_jia);//加
        imagebtn_jian = (ImageButton) findViewById(R.id.imagebtn_jian);//减
        tvNum = (TextView) findViewById(R.id.tv_Num);//数量
        tvPrice = (TextView) findViewById(R.id.tv_Price);//单价
        qrdd_tv_title  = (TextView) findViewById(R.id.qrdd_tv_title);//标题
        qrdd_tv_content  = (TextView) findViewById(R.id.qrdd_tv_content);//内容
        tvSum = (TextView) findViewById(R.id.tv_Sum);//共计
        zfspinner = (Spinner) findViewById(R.id.zhifu_spinner);//支付方式
        fsspinner = (Spinner) findViewById(R.id.skfs_spinner);//授课方式
        tvstudentName = (TextView) findViewById(R.id.tv_studentName);//收件人姓名
        tvstudentPhone = (TextView) findViewById(R.id.tv_studentPhone);//收件人电话
        tvstudentAddr =(TextView) findViewById(R.id.tv_studentAddr);///收件人地址
        time_editText = (EditText) findViewById(R.id.time_editText);//时间轴
        pickerDialog = new YMDDatePickerDialog(this,System.currentTimeMillis());
        time_editText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickerDialog.show();
            }
        });
        pickerDialog.setOnDateTimeSetListener(new YMDDatePickerDialog.OnDateTimeSetListener() {
            @Override
            public void OnDateTimeSet(AlertDialog dialog, long date) {
                time_editText.setText(Tool.getStringYMDate(date));
            }
        });
        //spinner
        stringArrayAdapter = new ArrayAdapter<String>(this,android.support.v7.appcompat.R.
                layout.support_simple_spinner_dropdown_item,items);
        zfspinner.setAdapter(stringArrayAdapter);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.support.v7.appcompat.R.
                layout.support_simple_spinner_dropdown_item,item);

        fsspinner.setAdapter(adapter);
    }

    private void clickListener() {
        /*
        添加按钮的点击事件
         */
        imagebtn_jia.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    int num = Integer.parseInt(tvNum.getText().toString());
                    int price = Integer.parseInt(tvPrice.getText().toString());
                    int sum = Integer.parseInt(tvSum.getText().toString());
                    if (num<=50&&num>=0){
                        num++;
                        sum+=price;
                        tvNum.setText(num+"");
                        tvSum.setText(sum+"");
                    }
                }
            });
         /*
        减少按钮的点击事件
         */
            imagebtn_jian.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    int num = Integer.parseInt(tvNum.getText().toString());
                    int price = Integer.parseInt(tvPrice.getText().toString());
                    int sum = Integer.parseInt(tvSum.getText().toString());
                    if (num>0){
                        num--;
                        sum=sum-price;
                        tvSum.setText(sum+"");
                        tvNum.setText(num+"");
                    }else{
                        Toast.makeText(ConfirmOrder.this, "已经是0了", Toast.LENGTH_SHORT).show();
                    }
                }
            });


        btn_OrdersConfirmation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(qrdd_keyongjifen.getText()) ||
                        TextUtils.isEmpty(time_editText.getText()) ||
                        TextUtils.isEmpty(tvNum.getText())) {
                    Toast.makeText(getApplication(), "您的订单中尚有未完善的部分\n" +
                            "请补充完整~", Toast.LENGTH_SHORT).show();
                } else {
                    payRequest();
                }
            }
        });
    }

    private void payRequest() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ConfirmOrder.this);
        builder
                .setTitle("确认支付")
                .setMessage("亲、您确定要支付吗？")//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override

                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        shoukejifen = qrdd_keyongjifen.getText().toString();
                        zfSpinner = zfspinner.getSelectedItem().toString();
                        fsSpinner = fsspinner.getSelectedItem().toString();
                        time = time_editText.getText().toString();
                        //初始化shareP
                        final String upLoadUrl = ThisUri.SERVER_YUMING + StudentUri.CONFIRMORDER;
                        //购买数量
                        String num = tvNum.getText() + "";

                        Log.e("test","recname "+recname+"\nrecphone "+recphone+"\nclassaddr "+classaddr+"\nclasstype "+fsSpinner+
                                "\nclasstime "+time+"\npaytype "+zfSpinner+"\npoints "+shoukejifen+"\nnum "+num+
                                "\nlessonid "+lessonID+"\nteacherid "+teacherID);

                        RequestParams params = new RequestParams(upLoadUrl);
                        params.setHeader("cookie", sessionID);
                        params.addBodyParameter("lessonid", lessonID+"");//课程ID
                        params.addBodyParameter("teacherid", teacherID+"");//老师ID
                        params.addBodyParameter("num", num);//购买数量
                        params.addBodyParameter("recphone", recphone);//收件人手机号码
                        params.addBodyParameter("recname", recname + ""); //收件人姓名
                        params.addBodyParameter("recaddr",  classaddr+"");//收货地址
                        params.addBodyParameter("classtype", fsSpinner);//授课方式
                        params.addBodyParameter("classtime", time);//授课时间
                        params.addBodyParameter("paytype", zfSpinner);//支付方式
                        params.addBodyParameter("points", shoukejifen + "");//可用积分
                        x.http().post(params, new Callback.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String result) {
                                Log.e("test", "我订单了" + result);
                                Message message = handler.obtainMessage();
                                message.what = 1;
                                message.obj = result;
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {

                            }

                            @Override
                            public void onCancelled(CancelledException cex) {

                            }

                            @Override
                            public void onFinished() {

                            }
                        });
                    }

                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮


            @Override

            public void onClick(DialogInterface dialog, int which) {//取消响应事件


                Log.i("alertdialog", " 请保存数据！");

            }

        }).show();//在按键响应事件中显示此对话框
    }

    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    String state = (String) msg.obj;
                    Log.e("test","订单结果"+state);
                    OrderReq orderReq = (new Gson()).fromJson(state, OrderReq.class);
                    if (orderReq.isSuccess()) {
                        unifiedOrder(orderReq);
                    }else{
                        Toast.makeText(ConfirmOrder.this, "订单失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 2:
                    String result = (String) msg.obj;
                    OrderSeverCallback callback = (new Gson()).fromJson(result, OrderSeverCallback.class);
                    if (callback.isSuccess()) {
                        if (WxUtil.check(ConfirmOrder.this, wxapi)) {
                            OrderSeverCallback.ObjBean ob = callback.getObj();
                            String appid = ob.getAppid();
                            String prepayId = ob.getPrepayid();
                            String nonceStr = ob.getNoncestr();
                            String partnerid = ob.getPartnerid();
                            String sign = ob.getSign();
                            String timestamp = ob.getTimestamp();

                            PayReq payReq = new PayReq();
                            payReq.appId = appid;
                            payReq.partnerId = partnerid;
                            payReq.prepayId = prepayId;
                            payReq.nonceStr = nonceStr;
                            payReq.timeStamp = timestamp;
                            payReq.packageValue = "Sign=WXPay";
                            payReq.sign = sign;
                            Log.e("test", "支付订单： " + result + "\npartnerid " + partnerid);
                            Toast.makeText(ConfirmOrder.this, "赶快支付吧！！！", Toast.LENGTH_SHORT).show();
                            wxapi.sendReq(payReq);
                        }
                    }else{
                        Toast.makeText(ConfirmOrder.this, "获取订单失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 3:
                    String result3= (String) msg.obj;
                    Log.e("test","学生请求地址ID "+result3);
                    if (result3!=null&&!result3.equals("")){
                        StudentAddr sa = (new Gson()).fromJson(result3, StudentAddr.class);
                        if (sa.isSuccess()) {
                            if (sa.getObj() != null) {
                                recname = sa.getObj().getPeople();
                                recphone = sa.getObj().getPhone();
                                classaddr = sa.getObj().getAddr();
                                tvstudentName.setText(sa.getObj().getPeople() + "");
                                tvstudentPhone.setText(sa.getObj().getPhone()+"");
                                tvstudentAddr.setText(sa.getObj().getAddr()+"");
                            }else{
                                Toast.makeText(ConfirmOrder.this, "您尚未添加地址", Toast.LENGTH_SHORT).show();
                            }
                        }else{
                            Toast.makeText(ConfirmOrder.this, "获取地址失败！", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
            }
        }
    };

    private void unifiedOrder(OrderReq orderReq) {
        progressDialog = ProgressDialog.show(this, null, "正在打开微信支付...", true, false);
        OrderReq.ObjBean obj = orderReq.getObj();
        int id = obj.getId(); //订单ID
        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + StudentUri.WECHAT_PAY);
        params.addHeader("cookie",sessionID);
        params.addBodyParameter("id", id + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("test","微信支付下单 "+result);
                Message msg=handler.obtainMessage();
                msg.what=2;
                msg.obj=result;
                handler.sendMessage(msg);
                progressDialog.dismiss();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {

            }
        });
    }
    //返回按钮
    public void querendingdan_fanhui(View view) {
        finish();
    }
    //  调用地图
    public void map(View view) {
        Intent intent = new Intent(this, AMapForStudent.class);
        startActivity(intent);
    }
    public int getSum() {
        return sum;
    }
    public void setSum(int sum) {
        this.sum = sum;
    }

}


